package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

//通过反射获取类
public class ReflectDemo01 {
    //获取类
    public static void demo01(){
        //获取反射方式（反射入口：class，1.Class.forName(全类名（包名+类名）)  2.类名.class  3.对象.getclass）

        //  1.Class.forName(全类名（包名+类名）)
        try {
            Class<?> perClazz = Class.forName("reflect.Person");
            System.out.println(perClazz);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


        //2.类名.class
        Class<?> perClazz2 = Person.class ;
        System.out.println(perClazz2);


        //3.对象.getclass
        Person per = new Person();
        Class<?> perClazz3 = per.getClass();
        System.out.println(perClazz3);
    }

    //获取方法
    public static void demo02(){
        //Class入口
        Class<?> perClazz = null;
        try {
            perClazz = Class.forName("reflect.Person");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //获取所有的 公共的方法
        Method[] methods = perClazz.getMethods();
        for (Method method: methods) {
            System.out.println(method);

        }
    }

    public static void demo03(){
        Class<?> perClazz = null;
        try {
            perClazz = Class.forName("reflect.Person");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Class<?>[] interfaces = perClazz.getInterfaces();
        for (Class<?>inter: interfaces) {
            System.out.println(inter);
        }
    }

    //获取所有的父类
    public static void demo04() {
        Class<?> perClazz = null;
        try {
            perClazz = Class.forName("reflect.Person");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Class<?> superclass = perClazz.getSuperclass();
    }


    //获取所有的构造方法
    public static void demo05() {
        Class<?> perClazz = null;
        try {
            perClazz = Class.forName("reflect.Person");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Constructor<?>[] constructors = perClazz.getConstructors();
        for (Constructor<?> constructor:constructors) {
            System.out.println(constructor);
        }
    }

    //获取所有的公共属性
    public static void demo06() {
        Class<?> perClazz = null;
        try {
            perClazz = Class.forName("reflect.Person");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Field[] fields = perClazz.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
    }
    public static void main(String[] args) {
        demo01();
        demo02();
        demo03();
        demo04();
        demo05();
        demo06();
    }
}
